package com.aidong.pay.action;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import com.aidong.drawCode.biz.DrawBiz;
import com.aidong.drawCode.entity.DrawCode;
import com.aidong.jobs.async.SmsTask;
import com.aidong.login.biz.MemberIntegralLogBiz;
import com.aidong.login.entity.MemberIntegralLog;
import com.aidong.pay.biz.MsmAppointmentToRemindBiz;
import com.aidong.pay.biz.OrderManagementBiz;
import com.aidong.pay.biz.OrdergeneratedBiz;
import com.aidong.pay.config.XMLUtil;
import com.aidong.pay.config.util.ClenderUtil;
import com.aidong.pay.entity.Recommend;
import com.aidong.util.IntegralAction;
import com.aidong.util.RandomUtil;

@ParentPackage("json")
@Namespace("/")
public class WeiChatReturnAction {

	private OrdergeneratedBiz ordergeneratedBiz;

	private MsmAppointmentToRemindBiz appointmentToRemindBiz;

	private OrderManagementBiz orderManagementBiz;

	private MemberIntegralLogBiz logBiz;
	
	@Autowired
	private DrawBiz drawBiz;
	
	
	@Autowired
	public void setOrdergeneratedBiz(OrdergeneratedBiz ordergeneratedBiz) {
		this.ordergeneratedBiz = ordergeneratedBiz;
	}

	@Autowired
	public void setAppointmentToRemindBiz(MsmAppointmentToRemindBiz appointmentToRemindBiz) {
		this.appointmentToRemindBiz = appointmentToRemindBiz;
	}

	@Autowired
	public void setOrderManagementBiz(OrderManagementBiz orderManagementBiz) {
		this.orderManagementBiz = orderManagementBiz;
	}

	@Autowired
	public void setLogBiz(MemberIntegralLogBiz logBiz) {
		this.logBiz = logBiz;
	}

	@Autowired
	SmsTask smsTask;

	/**
	 * 微信支付异步通知
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "wxpayreturn")
	public String weiChatReturnMethod() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();

		Map<String, String> map = XMLUtil.parseXml(request);
		System.out.println("微信支付回调：" + map);
		if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
			String openid = map.get("openid");// 用户在商户appid下的唯一标识
			String out_trade_no = map.get("out_trade_no"); // 商务订单号
			String trade_no = map.get("transaction_id"); // 交易流水号
			int total = Integer.parseInt(map.get("total_fee"));// 总金额
			double total_fee = total * 0.01d;
			// 回调记录
			Map<String, Object> backMap = new HashMap<String, Object>();
			try {
				backMap.put("orderId", Integer.valueOf(map.get("out_trade_no")));
				backMap.put("backTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				backMap.put("backType", 2);
				backMap.put("buyerUserId", openid);
				backMap.put("totalAmount", total_fee);
				backMap.put("tradeNo", trade_no);
			} catch (Exception e) {

			}
			orderManagementBiz.addPayCallBack(backMap);

			int orderId = Integer.valueOf(out_trade_no);
			Map<String, Object> disposeMap = ordergeneratedBiz.getPayOrderDispose(orderId);
			int applyFlg = Integer.valueOf(disposeMap.get("applyFlg").toString()); // 同步处理状态
			int orderType = Integer.valueOf(disposeMap.get("orderType").toString()); // 订单类型
			int subscribeId = Integer.valueOf(disposeMap.get("subscribeId").toString()); // 预约号
			String recommendCoach = null;
			if (disposeMap.get("recommendCoach") != null)
				recommendCoach = disposeMap.get("recommendCoach").toString();
			/**
			 * 获取和金额有关
			 */
			double actually = Double.parseDouble(disposeMap.get("actually").toString());// 实付金额
			String gmt_payment = "";
			DecimalFormat df = new DecimalFormat("#0.00");
			System.out.println("微信支付金额：" + df.format(total_fee) + "商品实付金额：" + df.format(actually));
			if (df.format(total_fee).equals(df.format(actually))) {
				String tickNo = "";
				if (applyFlg == 0) {
					Map<String, Object> memberMap = ordergeneratedBiz.getPayMemberPhone(orderId);
					tickNo = ClenderUtil.electronicTicketNo(memberMap.get("phoneNo").toString()); // 电子券号
					gmt_payment = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				}
				// 根据订单号 查询使用人的爱动号
				Map<String, Object> paraMap1 = new HashMap<String, Object>();
				paraMap1.put("orderId", orderId);
				Map<String, Object> statuMap = orderManagementBiz.getOrderBackStatus(paraMap1);
				int idongId = Integer.valueOf(statuMap.get("idongId").toString());
				int status = Integer.valueOf(statuMap.get("status").toString());
				Map<String, Object> paraMap = new HashMap<String, Object>();
				paraMap.put("orderId", orderId);
				paraMap.put("idongId", idongId);
				// 修改订单信息
				if (status == 0) {
					Map<String, Object> orderMap = new HashMap<String, Object>();
					orderMap.put("tickNo", tickNo);
					orderMap.put("orderId", orderId);
					orderMap.put("tradeNo", trade_no);
					orderMap.put("status", 1);
					orderMap.put("processId", 2);
					orderMap.put("payType", 2);
					orderMap.put("payTime", gmt_payment);
					orderManagementBiz.editOrderPayInfo(orderMap);

					// 修改预约状态
					Map<String, Object> subMap = new HashMap<String, Object>();
					subMap.put("applyType", orderType);
					subMap.put("subscribeId", subscribeId);
					subMap.put("status", 0);
					//orderManagementBiz.editAppointStatus(subMap);
					orderManagementBiz.editAppointCampaignStatus(subMap);
					// 修改兑换券或代金券表-此处无法判断使用的是代金券还是兑换券，故一起更新实际上会被更新的也只有一个

					orderManagementBiz.editCouponsInfo(paraMap);
					orderManagementBiz.editExchangeTicketsInfo(paraMap);
				}
				if (applyFlg == 0 && status == 0) { // 同步未处理
					
					if(orderType!=1){
						int cou=drawBiz.getDrawCountByNowTime(new Date());
						if(cou>0){
							//为新用户生成码
							DrawCode code=new DrawCode();
							code.setIdongId(idongId);
							code.setCode(RandomUtil.randDrawCode(4));
							if(orderType == 2){
								code.setBak("课程");
							}else if(orderType == 3){
								code.setBak("营养品");
							}else if(orderType == 4){
								code.setBak("健康餐");
							}else if(orderType == 5){
								code.setBak("装备");
							}else{
								code.setBak("未知");
							}
							drawBiz.addDrawCode(code);
						}
					}
					
					// 预约短信通知
					if (orderType == 1) { // 活动
						Map<String, Object> activityTypeMap = ordergeneratedBiz.getActivityType(orderId);
						int moviceFlag = Integer.valueOf(activityTypeMap.get("movieFlg").toString());

						Map<String, Object> mstMap = appointmentToRemindBiz.addCampaginRemind(orderId);
						String cellNumber = mstMap.get("phoneNo").toString(); // 电话号码
						String title = mstMap.get("title").toString(); // 活动标题
						String subscribeActiveId = mstMap.get("subscribeId").toString(); // 预约ID
						String date = mstMap.get("startTime").toString(); // 活动开始时间
						String address = mstMap.get("place").toString(); // 活动地点
						String voucherNo = mstMap.get("tickNo").toString(); // 券号
						if (moviceFlag == 0) {
							/*
							 * SMSUtil.pool.execute(new Runnable() { public void
							 * run() {
							 */
							try {
								// 手机号码后四位
								String latFourPhone = voucherNo.substring(voucherNo.length() - 4, voucherNo.length());
								// 电子券号前八位
								String topEight = voucherNo.substring(0, 8);
								// 短信提醒
								smsTask.activityRemind(cellNumber, title, subscribeActiveId, date, address, topEight,
										latFourPhone);
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else if (moviceFlag == 1) {
						}

					} else if (orderType == 2) { // 课程
						Map<String, Object> courseMap = appointmentToRemindBiz.addCourseRemind(orderId);
						String cellNumber = courseMap.get("phoneNo").toString(); // 电话号码
						String subscribeCourseId = courseMap.get("subscribeId").toString(); // 预约ID
						String courseName = courseMap.get("coureName").toString(); // 课程名
						String date = courseMap.get("subscribeDate").toString(); // 上课日期
						String time = courseMap.get("startTime").toString(); // 上课时间
						String dateTime = date + " " + time; // 上课开始时间
						String storeName = courseMap.get("storeName").toString(); // 场馆名
						String voucherNo = courseMap.get("tickNo").toString(); // 券号
						/*
						 * SMSUtil.pool.execute(new Runnable() { public void
						 * run() {
						 */
						try {
							// 手机号码后四位
							String latFourPhone = voucherNo.substring(voucherNo.length() - 4, voucherNo.length());
							// 电子券号前八位
							String topEight = voucherNo.substring(0, 8);
							// 短信提醒
							smsTask.courseAppointment(cellNumber, subscribeCourseId, courseName, dateTime, storeName,
									topEight, latFourPhone);

						} catch (Exception e) {
							e.printStackTrace();
						}
						/*
						 * } });
						 */
					} else if (orderType == 3 || orderType == 4 || orderType == 5) { // 健康餐饮
						Map<String, Object> foodMap = appointmentToRemindBiz.addFoodBuyRemind(orderId);
						String phoneNo = foodMap.get("phoneNo").toString(); // 电话号码
						String quantity = foodMap.get("quantity").toString(); // 数量
						String foodName = foodMap.get("foodName").toString(); // 餐名
						String buyDate = foodMap.get("buyDate").toString(); // 预订日期
						String pickUpForm = foodMap.get("pickUpForm").toString(); // 取餐开始日期
						String pickUpTo = foodMap.get("pickUpTo").toString(); // 取餐截止如期
						String pickDate = buyDate + " " + pickUpForm + "-" + pickUpTo;
						String storeName = foodMap.get("storeName").toString(); // 门店
						String voucherNo = foodMap.get("tickNo").toString(); // 电子券号
						String pickUpWay = foodMap.get("pickUpWay").toString(); // 取货方式
						/*
						 * SMSUtil.pool.execute(new Runnable() { public void
						 * run() {
						 */
						try {
							// 手机号码后四位
							String latFourPhone = voucherNo.substring(voucherNo.length() - 4, voucherNo.length());
							// 电子券号前八位
							String topEight = voucherNo.substring(0, 8);

							// 短信提醒
							if ("2".equals(pickUpWay)) {
								smsTask.foodAppointmentT(phoneNo, quantity, foodName);
							} else {
								smsTask.foodAppointment(phoneNo, quantity, foodName, pickDate, storeName, topEight,
										latFourPhone);
							}

						} catch (Exception e) {
							e.printStackTrace();
						}
						/*
						 * } });
						 */
					}
				}
				try {
					// 推荐返点计算
					if (!StringUtils.isBlank(recommendCoach)) {
						// 推荐返点计算
						Recommend recommend = orderManagementBiz.getRecommendInfo(out_trade_no);
						if (recommend != null && recommend.getRecommendIdongId() != 0
								&& recommend.getRecommendAmount() != 0) {
							logBiz.addLog(new MemberIntegralLog(recommend.getRecommendIdongId(),
									IntegralAction.order.getActionValue(),
									(new Double(recommend.getRecommendAmount())).intValue(), "订单号-" + out_trade_no));
						}
					}
				} catch (Exception e) {
				}
				response.getWriter().write(
						"<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
			}
		}
		return null;
	}
}
